package com.imranstechnology.homeexpensemanager;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TableRow;
import android.widget.TextView;

import com.imranstechnology.homeexpensemanager.utils.DateUtil;

public class ExpenseDetailView extends Activity {

	private ListView listViewRecords;
	private TableRow tableHeader;
	private List<ExpenseDetailEntity> expenseTransactions;
	private LayoutInflater inflater;
	private String [] vListCat;
	private Editor editor;
	private AlertDialog alertDialog;
	private Integer selectedPositionToDelete;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_expense_detail_view);
		SharedPreferences preferences = getSharedPreferences(HomeExpenseConstants.APP_PREPFERENCE_AREA, MODE_PRIVATE);
		editor = preferences.edit();
		 AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder.setMessage(R.string.delete_sure_msg)
	               .setPositiveButton(R.string.alert_yes_button, new DialogInterface.OnClickListener() {
	                   public void onClick(DialogInterface dialog, int id) {
	                	   deleteSelectedPosition(selectedPositionToDelete-1);
	                   }
	               })
	               .setNegativeButton(R.string.alert_cancel_button, new DialogInterface.OnClickListener() {
	                   public void onClick(DialogInterface dialog, int id) {
	                       alertDialog.cancel();
	                   }
	               });
	        // Create the AlertDialog object and return it
	        alertDialog = builder.create();		
	        inflater = getLayoutInflater();
		expenseTransactions = new ArrayList<ExpenseDetailEntity>();
		for(Integer year : ExpenseMemStore.EXPENSEE_ENTITY.getYearsTrnx().keySet())
		{
			expenseTransactions.addAll(ExpenseMemStore.EXPENSEE_ENTITY.getYearRecords(year));
		}
				
		Collections.sort(expenseTransactions, new Comparator<ExpenseDetailEntity>() {
			@Override
			public int compare(ExpenseDetailEntity lhs, ExpenseDetailEntity rhs) {
				if(rhs.getTransactionDate() == null ||lhs.getTransactionDate() == null)
					return 0;
				return rhs.getTransactionDate().compareTo(lhs.getTransactionDate());
			}
		});
		vListCat = getResources().getStringArray(R.array.expense_category);
		listViewRecords = (ListView)findViewById(R.id.dyanmic_list_view_table_);
		ListAdapter adapter = new ExpenseAdapter();
		listViewRecords.setAdapter(adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.options_menu, menu);
		return true;
	}
	private void deleteSelectedPosition(int pos){
		ExpenseDetailEntity det =  expenseTransactions.get(pos);
		ExpenseMemStore.addExpense(det.getExpenseAmount()*-1, det.getTransactionDate(), det.getExpenseCategory());
		ExpenseMemStore.storeMemExpense(editor);
	}
	private class ExpenseAdapter extends BaseAdapter{
		private TableRow renderedRow;
		
		public ExpenseAdapter() {
			super();
		}
		@Override
		public int getCount() {
			if(expenseTransactions == null)
				return 0;
			return expenseTransactions.size();
		}
		@Override
		public Object getItem(int position) {
			if(expenseTransactions == null)
				return null;
			return expenseTransactions.get(position);
		}
		@Override
		public long getItemId(int position) {
			if(expenseTransactions == null)
				return 0;
			return ((ExpenseDetailEntity)expenseTransactions.get(position)).getId();
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View tableRow = convertView;
			if(tableRow == null)
			{
				tableRow = inflater.inflate(R.layout.list_view_table_row, null);
			}
			tableRow.setOnLongClickListener(new View.OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					TextView view = (TextView) v.findViewById(R.id.id_table_row);
					if(view.getText() == null || view.getText().length() == 0)
						return false;
					String pos = view.getText().toString();
					selectedPositionToDelete = Integer.parseInt(pos);
					alertDialog.show();
					return true;
				}
			});
			ExpenseDetailEntity entity = expenseTransactions.get(position);
			TextView view = (TextView)tableRow.findViewById(R.id.id_table_row);
			view.setText(""+(position+1));
			view = (TextView)tableRow.findViewById(R.id.trnx_date_table_row);
			view.setText(""+DateUtil.dateToString(entity.getTransactionDate()));
			view = (TextView)tableRow.findViewById(R.id.category_date_table_row);
			view.setText(vListCat[entity.getExpenseCategory()]);
			view = (TextView)tableRow.findViewById(R.id.amount_date_table_row);
			view.setText(""+entity.getExpenseAmount());

			return tableRow;
		}
	};
}
